var map, drawController;
var vectorLayer;
var WGS_PROJECTION = new OpenLayers.Projection("EPSG:4326");
var SPHERICAL_MERCATOR_PROJECTION = new OpenLayers.Projection("EPSG:900913");
var styleMap;
var singleSelectControl, multipleSelectControl;


function init() {

	//STYLING
	var low = new OpenLayers.Rule({
		filter: new OpenLayers.Filter.Comparison({
			type: OpenLayers.Filter.Comparison.LESS_THAN,
			property: 'index',
			value: 2
		}),
		symbolizer: {
			fillColor: '${color}', fillOpacity:.8,
			pointRadius:20, strokeColor: '#ffffff',
			strokeWidth:5, fillOpacity: 0.3
		}
	});

	var mid = new OpenLayers.Rule({
		filter: new OpenLayers.Filter.Comparison({
			type: OpenLayers.Filter.Comparison.BETWEEN,
			property: 'index',
			lowerBoundary:2,
			upperBoundary:3
		}),
		symbolizer: {
			fillColor: '${color}', fillOpacity:.8,
			pointRadius:20, strokeColor: '#ffffff',
			strokeWidth:5, fillOpacity: 0.6
		}
	});

	var high = new OpenLayers.Rule({
		filter: new OpenLayers.Filter.Comparison({
			type: OpenLayers.Filter.Comparison.GREATER_THAN,
			property: 'index',
			value: 5
		}),
		symbolizer: {
			fillColor: '${color}', fillOpacity:.8,
			pointRadius:20, strokeColor: '#ffffff',
			strokeWidth:5, fillOpacity: 1
		}
	});

	var defaultStyle = new OpenLayers.Style({
			label: '${num_points}',
			fontColor: '#000000',
            fontFamily: 'arial, sans-serif',
            fontSize: '.9em',
            fontWeight: 'bold',
			graphicZIndex: 1
		},{
			context: {
				num_points: function(feature){
					if(feature.attributes.count > 1)
						return feature.attributes.count;
					else{
						return '';
					}
				}
			}
		});
	defaultStyle.addRules([low, mid, high]);

	var selectStyle = new OpenLayers.Style({
		'strokeColor': '#1307f1'
	});

	styleMap = new OpenLayers.StyleMap({
		'default': defaultStyle,
		'select': selectStyle
	});
	
	vectorLayer = new Array();

	//MAP
	map = new OpenLayers.Map("map", {
		controls: [],
		displayProjection: WGS_PROJECTION,
		restrictedExtent: new OpenLayers.Bounds(116.27, 4.39, 127, 21.53).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION)
	});
    var osm = new OpenLayers.Layer.Google('Google Map Layer', {});

	map.addLayers([osm]);
	singleSelectControl = new OpenLayers.Control.SelectFeature(
		vectorLayer,
		{
			displayClass: "singleSelect",
			title: 'Select single or multiple points. To select multiple points, hold shift key',
			clickout: true, toggle: true,
			multiple: false, hover: false,
			toggleKey: "ctrlKey",
			multipleKey: "shiftKey",
			box: false
		}
	);
	multipleSelectControl = new OpenLayers.Control.SelectFeature(
		vectorLayer,
		{
			displayClass: "multipleSelect",
			title: 'Select single or multiple points. To select multiple points, hold shift key',
			clickout: true, toggle: false,
			multiple: false, hover: false,
			toggleKey: "ctrlKey",
			multipleKey: "shiftKey",
			box: true
		}
	);
    
    //PANEL
	var zoomBox = new OpenLayers.Control.ZoomBox(
		{title:"Zoom box: Selecting it you can zoom on an area by clicking and dragging."});

	var zoomMax = new OpenLayers.Control.ZoomToMaxExtent({title:"Zoom to the max extent"});

	var mouseDefaults =  new OpenLayers.Control.MouseDefaults({
		title:'Default mouse configuration'
	});

	var panel = new OpenLayers.Control.Panel();
	panel.addControls([mouseDefaults, singleSelectControl, multipleSelectControl, zoomBox, zoomMax]);
	map.addControl(panel);

    drawController = new OpenLayers.Control.DrawFeature(vectorLayer, OpenLayers.Handler.Point, {featureAdded: onFeatureAdded});
	map.addControls(drawController);
	map.addControl(new OpenLayers.Control.MousePosition());

	map.setCenter(new OpenLayers.LonLat(121.06850, 14.64866).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION), 14);
}

function defineFeature(feature) {
	if( feature.cluster ){
    total = 0;
    size = feature.cluster.length;
    for(i=0; i<size; i++) {
      total += parseInt(feature.cluster[i].attributes.index);
    }
    feature.attributes.index = parseInt(total/size);
    feature.attributes.description = size + " Reports in this Cluster";
    feature.attributes.color = feature.cluster[size-1].attributes.color;
  }
}

//detail.html
function setMapCenter(lon, lat){
	 map.setCenter(new OpenLayers.LonLat(lon, lat).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION), 17);
}

//home.html
function addLayer(layerName){
	var layer = new OpenLayers.Layer.Vector(layerName, {
		styleMap: styleMap,
		rendererOptions: {zIndexing: true},
		preFeatureInsert: defineFeature,
		strategies: [new OpenLayers.Strategy.Cluster({threshold: 2, distance: 40})]
	});
	layer.styleMap = styleMap;
	
	//@home.html WHEN REPORTS ARE SELECTED, WRITES IN SIDEBAR
	layer.events.register('featureselected', this, on_select_feature);
	layer.events.register('featureunselected', this, on_unselect_feature);

	vectorLayer[layerName] = layer;
	map.addLayers([vectorLayer[layerName]]);
	
	var layers=new Array();
	var i = 0;
	for(x in vectorLayer)
	{
		layers.push(vectorLayer[x]);
		i=i+1;
	}
	singleSelectControl.setLayer(layers);
	multipleSelectControl.setLayer(layers);


}

//home.html
function on_select_feature(event){
    var info_div = document.getElementById('reportBoard');
    	info_div.innerHTML += '<div class="post"><h3 class="title">' +
        event.feature.attributes.title +
        '</h3><div class="entry">' +
        event.feature.attributes.description +
        '<br />' +
        event.feature.attributes.index_name + ': ' + event.feature.attributes.index_level_name +
        '</div></div>';
}
//home.html
function on_unselect_feature(event){
    var info_div = document.getElementById('reportBoard');
    info_div.innerHTML = '';
}

//in home.html
function get_reports(reports, layerName) {
	var format = new OpenLayers.Format.GeoJSON({internalProjection: SPHERICAL_MERCATOR_PROJECTION, externalProjection: WGS_PROJECTION});
    vectorLayer[layerName].removeAllFeatures();
	vectorLayer[layerName].addFeatures(format.read(reports));
}

//needed in submit
function onFeatureAdded(feature){
    vectorLayer.removeAllFeatures();
    vectorLayer.addFeatures(feature);
    mapPoint = new OpenLayers.Geometry.Point(feature.geometry.getBounds().getCenterLonLat().lon, feature.geometry.getBounds().getCenterLonLat().lat).transform(SPHERICAL_MERCATOR_PROJECTION, WGS_PROJECTION);
    lon = mapPoint.x;
    lat = mapPoint.y;
}

//in submit
function add_point(){
    var mapPoint = new OpenLayers.Geometry.Point(lon , lat).transform(WGS_PROJECTION, SPHERICAL_MERCATOR_PROJECTION);
    var newpoint = new OpenLayers.Feature.Vector(mapPoint, {description: desc, title: title, index: index});
    vectorLayer.addFeatures(newpoint);
}

//submit.html
function activateDrawFeature(){
	drawController.activate();
}
